import React, { FC, RefObject, useState } from 'react'
import { Button, Form, Steps, Input, DatePicker, Tag, ImageUploader, Toast, TextArea } from 'antd-mobile'
import { CheckCircleFill } from 'antd-mobile-icons'
import type { DatePickerRef } from 'antd-mobile/es/components/date-picker'
import dayjs from 'dayjs'
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader'



import MyHeader from '../../components/MyHeader'
import { tagList } from '../../utils/index'
import { addtravelsAPI, uplodafileAPI } from '../../api/api'
import { ShowMsg } from '../../utils/message'
import { useNavigate } from 'react-router-dom'


const Submit: FC = () => {
  const { Step } = Steps
  const router = useNavigate()
  const [count, setCount] = useState<number>(0)
  const [form] = Form.useForm()
  const [list, setList] = useState([...tagList.splice(1)])
  // 本地图片地址
  const [fileList, setFileList] = useState<ImageUploadItem[]>([])
  // 服务器图片地址
  const [imgList, setImgList] = useState<any>([])
  const [obj, setObj] = useState({})
  const [content, setContent] = useState<string>('')


  // 步骤条
  const steps = [
    {
      title: '第一步',
      desc: '记录游玩时间和地点'
    },
    {
      title: '第二步',
      desc: '记录游玩美好瞬间'
    },
    {
      title: '第三步',
      desc: '记录游玩感受心得'
    }
  ]

  // 下一步
  const gotonext = () => {
    if (count == 0) {
      form.validateFields()
        .then((value) => {
          setObj(value)
          setCount(count + 1)
        })
        .catch((err) => {
          ShowMsg('请填写完整信息')
        })
    } else if (count == 1) {
      if (list.filter((item: any) => item.check).length > 0 && imgList.length > 0) {
        setCount(count + 1)
      } else {
        ShowMsg('请选择标记以及上传图片')
      }
    }
  }

  // 标记选择逻辑
  const chooseItem = (item: any, index: any) => {
    if (list.filter((v: any) => v.check).length > 5 && !item.check) {
      ShowMsg('标记最多可选6个')
    } else {
      item.check = !item.check
      list.splice(index, 1, item)
      setList([...list])
    }
  }



  // 上一步
  const goPrev = () => {
    setCount(count - 1)
  }


  // 完成
  const submitData = async () => {
    if (content) {
      const params = {
        content,
        ...obj,
        tiem: new Date(),
        imgs: imgList,
        tags: list.filter((item: any) => item.check),
        likes: 0,
        collects: 0,
        pings: 0,
      }
      const res: any = await addtravelsAPI(params)
      if (res.code == 200) {
        const arr = list.map((item: any) => {
          item.check = false
          return item
        })
        setList(arr)
        ShowMsg('发布成功')
        router(-1)
      }
    } else {
      ShowMsg('请写下游玩的感受吧')
    }
  }




  // 图片上传
  const mockUpload = async (file: File) => {
    let data = new FormData()  // 新建一个表单对象  上传文件
    data.append('file', file)
    let res: any = await uplodafileAPI(data)
    if (res.code == 200) {
      imgList.push({
        url: res.path
      })

      setImgList([...imgList])
      return {
        url: URL.createObjectURL(file),
      }
    }
  }

  // 图片删除
  const onDelete = (item: ImageUploadItem, index: any) => {
    console.log(item);
    var index = fileList.findIndex(v => v.url == item.url) as any
    imgList.splice(index, 1)
    setImgList([...imgList])
  }

  return (
    <div>
      <MyHeader title='发 布 游 记'></MyHeader>

      <div className='submit-box'>
        <Steps
          direction='vertical'
          current={count}
          style={{
            '--title-font-size': '17px',
            '--description-font-size': '15px',
            '--indicator-margin-right': '12px',
            '--icon-size': '22px',
          }}>
          {
            steps.map((item: any, index: any) => {
              return (
                <Step
                  key={index}
                  title={item.title}
                  description={item.desc}
                  icon={<CheckCircleFill />}
                />
              )
            })
          }
        </Steps>

        <div style={{ padding: '5px' }}>
          {
            count == 0 &&
            <Form layout='vertical' form={form}>
              <Form.Item
                label='游玩标题'
                name='title'
                rules={[{ required: true, message: '标题不能为空' }]}
              >
                <Input placeholder='请输入游玩标题' clearable />
              </Form.Item>
              <Form.Item
                label='游玩地点'
                name='address'
                rules={[
                  { required: true, message: '地点不能为空' }
                ]}
              >
                <Input placeholder='请输入游玩地点' />
              </Form.Item>
              <Form.Item
                name='date'
                label='游玩时间'
                rules={[{ required: true, message: '请选择日期' }]}
                onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                  datePickerRef.current?.open()
                }}
              >
                <DatePicker
                  precision='minute'
                  onConfirm={date => form.setFieldValue('date', date)}
                >
                  {value =>
                    value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '请选择'
                  }
                </DatePicker>
              </Form.Item>
            </Form>
          }

          {
            count == 1 &&
            <div>
              <div>
                <div className="label" style={{ fontSize: 16, paddingBottom: '5px' }}>
                  游玩标签
                  <span style={{ fontSize: 10 }}>（最多可选6种）</span>
                </div>

                <div className='tagList' style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-start' }}>
                  {
                    list.map((item: any, index: any) => {
                      return (
                        <Tag
                          color={item.check ? '#ff6430' : item.color}
                          key={index}
                          style={{ margin: '5px' }}
                          onClick={() => chooseItem(item, index)}
                        >
                          {item.label}
                        </Tag>
                      )
                    })
                  }
                </div>

                <div>
                  <div className="label" style={{ fontSize: 16, paddingBottom: '5px' }}>
                    游玩照片
                    <span style={{ fontSize: 10 }}>（最多可上传9张）</span>
                  </div>

                  <ImageUploader
                    value={fileList}
                    onChange={setFileList}
                    upload={mockUpload}
                    multiple
                    maxCount={9}
                    onDelete={onDelete}
                  />
                </div>
              </div>
            </div>
          }

          {
            count == 2 &&
            <div>
              <div className='content'>
                <div style={{ fontSize: '16px' }}>
                  游玩感受心得
                  <span style={{ fontSize: '12px' }}>（说点什么吧）</span>
                </div>

                <div>
                  <TextArea
                    value={content}
                    onChange={setContent}
                    defaultValue={''}
                    placeholder='请输入游玩心得'
                    className='mt20'
                    style={{ border: '1px solid #ddd', borderRadius: 5, padding: 10 }}
                    showCount
                    maxLength={500}
                    rows={8}
                  />
                </div>
              </div>
            </div>
          }

        </div>




      </div>

      <div className='btns' style={{ display: 'flex', justifyContent: 'space-evenly', marginTop: '30px' }}>
        {
          count != 0 && <Button size='middle' color="success" onClick={goPrev}>上一步</Button>
        }
        {
          count != steps.length - 1 && <Button size='middle' color="primary" onClick={gotonext}>下一步</Button>
        }
        {
          count == steps.length - 1 && <Button size='middle' color="warning" onClick={submitData}>完 成</Button>
        }
      </div>

    </div>
  )
}

export default Submit
